//
//  HMDoctorService.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/8/22.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON
/// 头部
class HMDoctorService: HMViewController {
    
    // 列表数据
    var dsList = Array<Any>()
    let lattice1 =  homeIconView()
    let lattice2 =  homeIconView()
    let bgImageView = UIImageView()
    private lazy var table: UITableView = {
       let _table = UITableView()
        _table.delegate = self
        _table.dataSource = self
//        _table.backgroundColor = UIColor.white
        _table.register(HMSessionCell.classForCoder(), forCellReuseIdentifier: "HMSessionCell")
        return _table
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 获取正在沟通的健康咨询列表
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "user/consult/communicating", parameters: [:], success: { (json) in
            print("====>>", json)
            let code = json["code"].intValue
            if code == 0 {
                
                self.dsList = json["data"].arrayValue
                self.table.reloadData()
                self.table.isHidden = false
                
            }else {
                //其他错误
                 self.table.isHidden = true
            }
            
            
        }, fail: { (code, err) in
            print("=====>",code, err)
        }) {
            
        }
        
    }
    
    override func setupView() {
        
         self.title = "医生服务"
        view.backgroundColor = configure.shareConfigure.HMColor2
        view.addSubview(lattice1)
        view.addSubview(lattice2)
        view.addSubview(bgImageView)
        view.addSubview(table)
        
        
        
        lattice1.leadingAlign(view: view, predicate: "0")
        lattice1.topAlign(view: view, predicate: "0")
        lattice1.backgroundColor = .white
        lattice1.setData(imgName: "医生", title: "健康咨询")
        lattice1.tag = 1110
        lattice1.delegate = self //as! homeIconViewDelegate
        lattice1.heightConstrain(predicate: "120")
        lattice1.width(view: view, predicate: "*0.5")
        lattice1.addLayer(isAddLayer: (false, false, true, false), color: configure.shareConfigure.HMColor3, crude: 1, layout: (w: (view.wWidth/2), h:120))
        
        lattice2.leadingHorizontally(view: lattice1, predicate: "1")
        lattice2.topAlign(view: view, predicate: "0")
        lattice2.setData(imgName: "药物建议", title: "药物建议")
        lattice2.backgroundColor = .white
        lattice2.tag = 1111
        lattice2.delegate = self
        lattice2.heightConstrain(predicate: "120")
        lattice2.width(view: view, predicate: "*0.5")
        
        
        
        
        table.topVertically(view: lattice1, predicate: "\(10)")
        let h = view.wHeight - 120
        table.heightConstrain(predicate: "\(h)")
        table.leadingAlign(view: view, predicate: "0")
        table.trailingAlign(view: view, predicate: "0")
        table.isHidden = true
        
        
        bgImageView.image = UIImage.init(named: "list_null")
        bgImageView.centerXYAlign(view: view)
        
    }
   
}


extension HMDoctorService : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dsList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return  88
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = table.dequeueReusableCell(withIdentifier: "HMSessionCell") as! HMSessionCell
        cell.isTitleStr = self.title!
        cell.isDoctor = true
        cell.setJson(json: self.dsList[indexPath.row] as! JSON)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! HMSessionCell
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging

        // 拿到对应的会话
        let dic = self.dsList[indexPath.row] as! JSON
        let doctorIdStr = dic["doctorId"].stringValue
//        let consultId = dic["id"].stringValue
        let con :TIMConversation =   HMPlatform.getSomeoneConversation(doctorIdStr)
        _im.conversation = con
        _im.im_doctorId = con.getReceiver()
        _im.im_consultId = dic["id"].stringValue
        _im.userProfile = dic
        if cell.userProfile != nil {
            _im.doctorProfile = cell.userProfile!
        }
       _im.dataAry =   con.getLastMsgs(20)   //cell.messageList!
        self.pushViewController(_im)
    }
    
}

extension HMDoctorService: homeIconViewDelegate {
    func viewTapClick(view: UIView) {
        if view.tag == 1111 {
            // 进入医生服务
            // 0：全部，1：家庭医生，2：健康咨询
            let drug = HMProposalDrug()
            drug.info = ["sign": "用药建议"]
            drug.title = "用药建议"
        
            drug.variableTitles = ["全部", "健康咨询"]
            let oneVc  = HMProposalAll()
            oneVc._signStr = "0"
            oneVc.titleSign = drug.title!
            let twoVc = HMProposalAll()
            twoVc._signStr = "2"
            twoVc.titleSign = drug.title!
            drug.variableControllers = [oneVc, twoVc]
            self.pushViewController(drug)
        }else {
            // 进入健康咨询
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "user/consult-item-config", parameters: [:], success: { (json) in
                let health  = HMHealthCounseling()
                health.levelList = json["data"]["level"]
                health.officeList = json["data"]["office"]
                health.commTypeList = json["data"]["commType"]
                health.regionList = json["data"]["region"]

                self.pushViewController(health)
            }, fail: { (code, msg) in
                print("------->>>", msg)
            }) {}
        }
        
    }

}

extension HMDoctorService: HMSessionCellDelegate {
    func sessionCellBtn(sender: UIButton, doctor: Bool) {
        print("sender------->\(sender)")
//        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
//        let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
//        self.pushViewController(_im)
    }
    

}

